//
//  KESpeechManager.swift
//  KoalaEn
//
//  Created by Wade on 2024/9/13.
//

import Foundation
import SwiftAudioPlayer
import AVFoundation
//import SpeechEngineAsrToB
//import SpeechEngineTtsToB

class KEAudioManager:NSObject, ZFAudioPlayerDelegate{

    let audioPlayer = ZFAudioPlayer()
    let synthesizer = AVSpeechSynthesizer()
    var mzhText:String = ""
    // 静态常量只能初始化一次
    static let sharedInstance = KEAudioManager()
    // 在私有初始化方法配置
    
    /*
     pleased、sorry、annoyed、customer_service、professional、serious、happy、sad、angry、scare、hate、surprise、tear、conniving、comfort、radio、lovey-dovey、tsundere、charming、yoga、storytelling
     22种情感/风格】通用、愉悦、抱歉、嗔怪、开心、愤怒、惊讶、厌恶、悲伤、害怕、哭腔、客服、专业、严肃、傲娇、安慰鼓励、绿茶、娇媚、情感电台、撒娇、瑜伽、讲故事
     
     教育场景       voice_type
     知性姐姐-双语    BV034_streaming    ✔
     温柔小哥    BV033_streaming    ✔
     */
    private override init() {
        
//        speechEngine.setStringParam(SE_LOG_LEVEL_DEBUG, forKey: SE_PARAMS_KEY_LOG_LEVEL_STRING)
//        speechEngine.setStringParam("test_user_id", forKey: SE_PARAMS_KEY_UID_STRING)
//        // appid
//        speechEngine.setStringParam("1254461879", forKey: SE_PARAMS_KEY_APP_ID_STRING)
//
//        // token
//        speechEngine.setStringParam("Bearer;KEyKVw4MNDpM5VpoCNhNZtsrTOeoefh2", forKey: SE_PARAMS_KEY_APP_TOKEN_STRING)
////        speechEngine.setDelegate(self)
//
//        // 设置音频发音人
//        speechEngine.setStringParam("BV034_streaming", forKey: SE_PARAMS_KEY_TTS_VOICE_ONLINE_STRING)
//        //设置音频风格
//        speechEngine.setStringParam("happy", forKey: SE_PARAMS_KEY_TTS_VOICE_TYPE_ONLINE_STRING)
    }
    static func getInstance() -> KEAudioManager {
           return sharedInstance
    }
    
    func playEn(en text:String,zh zhText:String){
        if(text.length==0) {
            return
        }
        self.audioPlayer.delegate = self
        mzhText = zhText;
        synthesizer.stopSpeaking(at: .immediate)
        let words = text.replacingOccurrences(of: " ", with: "")
        let audioCachePath = FilePathUtils.cachePathWithPath(filePath: "KoalaEN/Audios")
        let filePath = audioCachePath + "/" + words + ".mp3";
        let audioFileURL = URL.init(fileURLWithPath: filePath)
        print(audioFileURL.absoluteString)
        if(FileManager.default.fileExists(atPath: filePath)){
            print("本地存在音频："+audioFileURL.absoluteString)
            self.audioPlayer.playLocalAudio(audioFileURL)
        }else{
            let audioURLString = "https://dict.youdao.com/dictvoice?audio=" + text + "&type=2"
            // 自定义字符集
            let customAllowedSet = CharacterSet.urlQueryAllowed.union(.init(charactersIn: "&+="))
             
            // 对整个URL进行编码
            if let encodedURL = audioURLString.addingPercentEncoding(withAllowedCharacters: customAllowedSet) {
                guard  let url = URL(string: encodedURL) else{return}
                let session = URLSession.shared
                session.dataTask(with: URLRequest(url: url)) { data, response, error in
                    guard let resData = data else { return  }
                    if(resData.count > 0){
                        try! data?.write(to: audioFileURL)
                        print("下载音频："+audioFileURL.absoluteString)
                        self.audioPlayer.playLocalAudio(audioFileURL)
                       
                    }
                }.resume()
            } else {
                print("Failed to encode URL.")
            }
        
        }
    }
    
    func audioplayerDidFinished(_ player: ZFAudioPlayer, success: Bool) {
        if mzhText.length > 0 {
            print("读取中文："+mzhText)
            // 创建语音输入实例
            let utterance = AVSpeechUtterance(string: mzhText)
             
            // 可以设置语速和语调
            utterance.rate = 0.4 // 0.5倍的语速
            utterance.pitchMultiplier = 1 // 正常语调
            utterance.volume = 1.0 // 音量
             
            // 设置语言（可选）
            utterance.voice = AVSpeechSynthesisVoice(language: "zh-CN")
           
            // 开始语音合成
            synthesizer.speak(utterance)
        }
       
    }
    
}
